﻿namespace JobButenko.Models.BusinessLogicLayer
{
    using System;
    using System.Linq;
    using System.Web;

    public class ResumeDocRepository
    {
        private readonly JobDataContext dataContext;

        public ResumeDocRepository(JobDataContext dataContext)
        {
            this.dataContext = dataContext;
        }

        public int UploadDoc(HttpPostedFileBase file)
        {
            int streamSize = Convert.ToInt32(file.InputStream.Length);
            var bufferFile = new byte[streamSize];
            file.InputStream.Read(bufferFile, 0, streamSize);
            var resumeDoc = new ResumeDoc
                                {
                                    ResumeDocument = bufferFile,
                                };
            this.dataContext.ResumeDocs.InsertOnSubmit(resumeDoc);
            this.dataContext.SubmitChanges();

            return resumeDoc.ResumeDocId;
        }

        private ResumeDoc GetResumeDoc(int id)
        {
            return this.dataContext.ResumeDocs.SingleOrDefault(d => d.ResumeDocId.Equals(id));
        }

        public byte[] GetByteResumeDoc(int id)
        {
            return
                this.dataContext.ResumeDocs.Where(r => r.ResumeDocId.Equals(id)).Select(s => s.ResumeDocument).First().ToArray();
        }

        public void DeleteResumeDoc(int id)
        {
            this.dataContext.ResumeDocs.DeleteOnSubmit(this.GetResumeDoc(id));
            this.dataContext.SubmitChanges();
        }

        public int UpdateResumeDoc(int id, HttpPostedFileBase file)
        {
            var streamSize = Convert.ToInt32(file.InputStream.Length);
            var bufferFile = new byte[streamSize];
            file.InputStream.Read(bufferFile, 0, streamSize);
            var resumeDoc = this.GetResumeDoc(id);

            resumeDoc.ResumeDocument = bufferFile;

            this.dataContext.SubmitChanges();
            return resumeDoc.ResumeDocId;
        }
    }
}